<?php
/**
 * Created by PhpStorm.
 * User: MSQ
 * Date: 2021/9/30
 * Time: 11:13
 */

namespace App\Task;


use App\Utils\LogHelp;
use App\Utils\RedisHelp;
use App\Utils\WebSocketMessage;
use EasySwoole\Task\AbstractInterface\TaskInterface;
use Throwable;

/**
 * Class WebSocketTask
 * @package App\Task
 * @property string $action
 * @property array $data
 */
class WebSocketTask implements TaskInterface
{
    protected $action;
    protected $data;

    public function __construct(string $action, array $data)
    {
        // 执行方法
        $this->action = $action;

        // 保存投递过来的数据
        $this->data = $data;
    }

    public function run(int $taskId, int $workerIndex)
    {
        $action = $this->action;
        $this->$action();
    }

    public function onException(Throwable $throwable, int $taskId, int $workerIndex)
    {
        // 异常处理
        $data = $this->data;
        $dataStr = isset($data['req']) ? $data['req']->serializeToJsonString() : json_encode($this->data);

        $msg = "任务类型:{$this->action}; task_id:{$taskId}, work_id: {$workerIndex}; data:{$dataStr};\n\n{$throwable->__toString()}";
        LogHelp::error($msg, 'websocket_task');
    }

    /**
     * 通知白友输液大厅
     */
    protected function send2By()
    {
        $data = $this->data;

        $projectId = $data['projectId'];
        $msgType = $data['msgType'];
        $content = $data['content'];

        // 根据wechatid找通道
        $redis = new RedisHelp();
        $list = $redis->getByProjectFd($projectId);

        if ($list) {
            foreach ($list as $fd) {
                WebSocketMessage::sendToFd($fd, $msgType, $content, WebSocketMessage::CheckTypeBy);
            }
        }
    }

    /**
     * 通知呼叫大屏
     */
    protected function send2CallScreen()
    {
        $data = $this->data;

        $projectId = $data['projectId'];
        $msgType = $data['msgType'];
        $content = $data['content'];

        // 根据wechatid找通道
        $redis = new RedisHelp();
        $list = $redis->getScreenProjectFd($projectId);

        if ($list) {
            foreach ($list as $fd) {
                WebSocketMessage::sendToFd($fd, $msgType, $content, WebSocketMessage::CheckTypeScreen);
            }
        }
    }
}
